package sample.servlet;

import fri.businessLayer.UserBeanRemote;
import fri.entiry.FrUser;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginController extends HttpServlet {
    
    @EJB
    private UserBeanRemote userBeanRemote;
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            String action = request.getParameter("action");
            if (action != null) {
                if (action.equals("Login")) {
                    String txtEmail     = request.getParameter("txtEmail");
                    String txtPassword  = request.getParameter("txtPassword");
                    FrUser frUser       = new FrUser();
                    frUser.setEmail(txtEmail);
                    frUser.setPassword(txtPassword);

                    if (userBeanRemote.checkLogin(frUser)) {
                        frUser                  = userBeanRemote.getUserByEmail(txtEmail);
                        HttpSession session     = request.getSession(true);
                        session.setAttribute("STATUS_LOGIN", 1);
                        session.setAttribute("USER_LOGIN", frUser);
                        RequestDispatcher rd    = request.getRequestDispatcher("reqHome.jsp");
                        rd.forward(request, response);
                    }
                }
            }
            RequestDispatcher rd = request.getRequestDispatcher("reqLogin.jsp");
            rd.forward(request, response);
        } finally {
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
